package com.imooc.miaosha.controller;

import com.imooc.miaosha.domian.User;
import com.imooc.miaosha.redis.keys.GoodsKey;
import com.imooc.miaosha.redis.RedisFactory;
import com.imooc.miaosha.result.Result;
import com.imooc.miaosha.service.GoodsService;
import com.imooc.miaosha.vo.GoodsDetailVO;
import com.imooc.miaosha.vo.GoodsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 模块描述: <br>
 * (商品控制器)
 *
 * @Author: Mr. xyb
 * @Date: 2019/4/17 0:38
 * @since: 1.8.0
 * @version: 1.0.0
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

    /**
     * 进入商品列表页面
     * (UserArgumentResolver User参数封装)
     *
     * @param model
     * @param user
     * @return
     */
    @RequestMapping("/to_list")
    public String toList(Model model,
                         // @CookieValue(value = CookieConstant.COOKIE_NAME_TOKEN, required = false) String cookieToken,
                         // @RequestParam(value = CookieConstant.COOKIE_NAME_TOKEN, required = false) String paramToken,
                         User user) {
        List<GoodsVO> goodsVOS = goodsService.listGoodsVo();
        model.addAttribute("goodsList", goodsVOS);
        model.addAttribute("user", user);
        return "goods_list";
    }

    /**
     * 页面缓存，使用redis以及WebContext类实现页面缓存技术
     *
     * @param model
     * @param user
     * @param response
     * @param request
     * @return
     */
    @RequestMapping(value = "to_list_cache", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toListCache(Model model, User user, HttpServletResponse response, HttpServletRequest request) {
        String html = redisFactory.get(GoodsKey.goodsList, "", String.class);
        if (!StringUtils.isEmpty(html)) {
            return html;
        }
        List<GoodsVO> goodsVOS = goodsService.listGoodsVo();
        model.addAttribute("goodsList", goodsVOS);
        model.addAttribute("user", user);
        WebContext webContext = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        String goods_list = thymeleafViewResolver.getTemplateEngine().process("goods_list", webContext);
        if (!StringUtils.isEmpty(goods_list)) {
            GoodsKey goodsKey = GoodsKey.goodsList;
            goodsKey.setExpireSeconds(60);
            redisFactory.set(goodsKey, "", goods_list);
        }
        return goods_list;
    }

    /**
     * 商品详情页(静态化)
     *
     * @param model
     * @param user
     * @param goodsId
     * @return
     */
    @GetMapping("/detail/{goodsId}")
    @ResponseBody
    public Result<GoodsDetailVO> toDetail(Model model, User user, @PathVariable("goodsId") Long goodsId) {


        GoodsVO goodsVO = goodsService.getGoodsVoByGoodsId(goodsId);

        long startDate = goodsVO.getStartDate().getTime();
        long endDate = goodsVO.getEndDate().getTime();
        long now = System.currentTimeMillis();
        // 秒杀未开始
        int goodsStatus = 0;
        // 距离秒杀开始时间
        int remainSeconds = (int) (startDate - now) / 1000;
        if (now >= endDate) {
            // 秒杀结束
            goodsStatus = 2;
            remainSeconds = -1;
        } else if (now >= startDate) {
            // 秒杀进行中
            goodsStatus = 1;
            remainSeconds = 0;
        }
        GoodsDetailVO goodsDetailVO = new GoodsDetailVO();
        goodsDetailVO.setGoodsVO(goodsVO);
        goodsDetailVO.setMiaoshaStatus(goodsStatus);
        goodsDetailVO.setRemainSeconds(remainSeconds);
        goodsDetailVO.setUser(user);

        return Result.success(goodsDetailVO);
    }


    /**
     * 商品详情页
     *
     * @param model
     * @param user
     * @param goodsId
     * @return
     */
    @GetMapping("/to_detail2/{goodsId}")
    public String toDetail2(Model model, User user, @PathVariable("goodsId") Long goodsId) {

        model.addAttribute("user", user);

        GoodsVO goodsVO = goodsService.getGoodsVoByGoodsId(goodsId);

        model.addAttribute("goods", goodsVO);
        long startDate = goodsVO.getStartDate().getTime();
        long endDate = goodsVO.getEndDate().getTime();
        long now = System.currentTimeMillis();
        // 秒杀未开始
        int goodsStatus = 0;
        // 距离秒杀开始时间
        int remainSeconds = (int) (startDate - now) / 1000;
        if (now >= endDate) {
            // 秒杀结束
            goodsStatus = 2;
            remainSeconds = -1;
        } else if (now >= startDate) {
            // 秒杀进行中
            goodsStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("miaoshaStatus", goodsStatus);
        model.addAttribute("remainSeconds", remainSeconds);
        model.addAttribute("endDateTime", endDate);


        return "goods_detail";
    }


    /**
     * 商品详情页
     * 优化url缓存
     *
     * @param model
     * @param user
     * @param goodsId
     * @return
     */
    @GetMapping(value = "/to_detail_url_cache/{goodsId}", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toDetailUrlCache(HttpServletRequest request, HttpServletResponse response, Model model,
                                   User user, @PathVariable("goodsId") Long goodsId) {

        String html = redisFactory.get(GoodsKey.goodsDetail, "" + goodsId, String.class);
        if (!StringUtils.isEmpty(html)) {
            return html;
        }

        model.addAttribute("user", user);

        GoodsVO goodsVO = goodsService.getGoodsVoByGoodsId(goodsId);

        model.addAttribute("goods", goodsVO);
        long startDate = goodsVO.getStartDate().getTime();
        long endDate = goodsVO.getEndDate().getTime();
        long now = System.currentTimeMillis();
        // 秒杀未开始
        int goodsStatus = 0;
        // 距离秒杀开始时间
        int remainSeconds = (int) (startDate - now) / 1000;
        if (now >= endDate) {
            // 秒杀结束
            goodsStatus = 2;
            remainSeconds = -1;
        } else if (now >= startDate) {
            // 秒杀进行中
            goodsStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("miaoshaStatus", goodsStatus);
        model.addAttribute("remainSeconds", remainSeconds);
        model.addAttribute("endDateTime", endDate);
        WebContext webContext = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        String goodsDetail = thymeleafViewResolver.getTemplateEngine().process("goods_detail", webContext);
        if (!StringUtils.isEmpty(goodsDetail)) {
            GoodsKey goodsKey = GoodsKey.goodsDetail;
            goodsKey.setExpireSeconds(60);
            redisFactory.set(goodsKey, "" + goodsId, goodsDetail);
        }
        return goodsDetail;

    }


    @Autowired
    private GoodsService goodsService;

    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    @Autowired
    private RedisFactory redisFactory;
}
